package br.ufrgs.tcp.async;

import java.io.IOException;
import java.util.List;

import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import br.ufrgs.tcp.async.base.ITaskDispatcher;
import br.ufrgs.tcp.model.IModel;
import br.ufrgs.tcp.model.ModelType;
import br.ufrgs.tcp.util.AppConstants;
import br.ufrgs.tcp.util.AppRandoms;

public class FetchDataTask<T extends IModel> extends AsyncTask<T,String,ModelType> {

	private FragmentActivity attachedActivity;
	private ITaskDispatcher parentObject;

	public FetchDataTask(FragmentActivity activity, ITaskDispatcher parent)  {
		attachedActivity = activity;
		parentObject = parent;
	}

	@Override
	protected void onProgressUpdate(String... values) {
		if(attachedActivity != null){
			parentObject.reportUpdate(values[0]);
		}
		super.onProgressUpdate(values);
	}

	@Override
	protected ModelType doInBackground(T... params) {		
		publishProgress("Buscando " + params[0].getModelName());
		List<? extends IModel> resultList;
		try {
			
			resultList = fetchData(params);
			publishProgress(params[0].getModelName() + ": Busca completa. Salvando dados no banco...");		
			saveData(resultList, params);
			publishProgress(params[0].getModelName() + ": Dados sincronizados.");
			return params[0].getModelType();
			
		} catch (InterruptedException e) {
			e.printStackTrace();
			return null;
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private void saveData(List<? extends IModel> resultList, T...params) throws InterruptedException {	
		if (AppConstants.DEBUG) 
			Thread.sleep(AppRandoms.getRandomSleepTime());	
		params[0].updateDataBase(resultList);
	
	}

	private List<? extends IModel> fetchData(T... params) throws InterruptedException, IOException {
		
		if (AppConstants.DEBUG) 
			Thread.sleep(AppRandoms.getRandomSleepTime());			
		List<? extends IModel> resultList = params[0].fetchData();
		return resultList;
	}
	
	@Override
	protected void onPostExecute(ModelType result) {
		super.onPostExecute(result);
		parentObject.reportEnd(result);
	}

}
